package com.book.book.service;

import com.book.book.domain.BookInfo;
import com.book.book.domain.Borrow;
import com.book.book.domain.User;
import com.book.book.mapper.BookInfoMapper;
import com.book.book.mapper.BorrowMapper;
import com.book.book.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BookInfoMapper bookInfoMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 辅助方法：填充 Borrow 对象中的 bookName, userName 和 status
     * @param borrowList 借阅记录列表
     */
    private void populateBookAndUserNames(List<Borrow> borrowList) {
        if (borrowList == null || borrowList.isEmpty()) {
            return;
        }

        for (Borrow borrow : borrowList) {
            // 填充 bookName
            if (borrow.getBookname() == null && borrow.getBookid() != null) {
                BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(borrow.getBookid().longValue());
                if (bookInfo != null) {
                    borrow.setBookname(bookInfo.getBookname());
                }
            }
            // 填充 userName
            if (borrow.getUsername() == null && borrow.getUserid() != null) {
                User user = userMapper.selectByPrimaryKey(borrow.getUserid().longValue());
                if (user != null) {
                    borrow.setUsername(user.getUsername());
                }
            }
            // 关键修改：根据 returnTime 设置 status 字段
            if (borrow.getReturntime() == null) {
                borrow.setStatus(0); // 借阅中
            } else {
                borrow.setStatus(1); // 已归还
            }
        }
    }

    /**
     * 借阅图书
     * @param bookid 图书ID
     * @param userid 用户ID
     * @param username 用户名 (从前端或会话中获取)
     * @return 借阅是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean borrowBook(Integer bookid, Integer userid, String username) {
        // 1. 检查图书是否存在且未被借出
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(bookid.longValue());
        if (bookInfo == null) {
            throw new RuntimeException("图书不存在");
        }
        if (bookInfo.getIsborrowed() == 1) {
            throw new RuntimeException("该图书已被借出，无法借阅");
        }

        // 2. 检查用户是否存在
        User user = userMapper.selectByPrimaryKey(userid.longValue());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 3. 检查用户是否已借阅此书且未归还 (防止重复借阅同一本未归还的书)
        Borrow activeBorrow = borrowMapper.selectActiveBorrowByBookAndUser(bookid, userid);
        if (activeBorrow != null) {
            throw new RuntimeException("您已借阅该图书，请勿重复借阅");
        }

        // 4. 创建借阅记录
        Borrow borrow = new Borrow();
        borrow.setBookid(bookid);
        borrow.setUserid(userid);
        borrow.setBookname(bookInfo.getBookname());
        borrow.setUsername(user.getUsername());
        borrow.setBorrowtime(new Date()); // 借阅时间为当前时间
        borrow.setReturntime(null); // 借阅时归还时间为null，表示当前借阅中

        int insertResult = borrowMapper.insertSelective(borrow);
        if (insertResult <= 0) {
            throw new RuntimeException("创建借阅记录失败");
        }

        // 5. 更新图书状态为已借出
        bookInfo.setIsborrowed(1); // 1: 已借出
        int updateResult = bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
        if (updateResult <= 0) {
            throw new RuntimeException("更新图书状态失败");
        }
        return true;
    }

    /**
     * 归还图书
     * @param borrowid 借阅记录ID
     * @return 归还是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean returnBook(Integer borrowid) {
        // 1. 获取借阅记录
        Borrow borrow = borrowMapper.selectByPrimaryKey(borrowid.longValue());
        if (borrow == null) {
            throw new RuntimeException("借阅记录不存在");
        }
        if (borrow.getReturntime() != null) {
            throw new RuntimeException("该图书已归还，请勿重复操作");
        }

        // 2. 更新借阅记录的归还时间为当前时间
        borrow.setReturntime(new Date());
        int updateBorrowResult = borrowMapper.updateByPrimaryKeySelective(borrow);
        if (updateBorrowResult <= 0) {
            throw new RuntimeException("更新借阅记录失败");
        }

        // 3. 更新图书状态为未借出
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(borrow.getBookid().longValue());
        if (bookInfo != null) {
            bookInfo.setIsborrowed(0); // 0: 未借出
            int updateBookResult = bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
            if (updateBookResult <= 0) {
                throw new RuntimeException("更新图书状态失败");
            }
        } else {
            System.err.println("归还图书时未找到对应的BookInfo，BookID: " + borrow.getBookid());
            throw new RuntimeException("归还失败：未找到对应的图书信息");
        }
        return true;
    }

    /**
     * 获取用户所有借阅历史 (分页) - returnTime IS NOT NULL 或 returnTime IS NULL
     * @param userid 用户ID
     * @param pagenum 当前页码
     * @return PageInfo<Borrow> 借阅记录分页信息
     */
    public PageInfo<Borrow> getUserBorrows(Integer userid, Integer pagenum) {
        PageHelper.startPage(pagenum, 10, "borrowTime desc");
        List<Borrow> list = borrowMapper.selectByUserId(userid, null, null);
        populateBookAndUserNames(list); // 填充书名、用户名和状态
        return new PageInfo<>(list);
    }

    /**
     * 获取用户当前借阅中的图书 (分页) - returnTime IS NULL
     * @param userid 用户ID
     * @param pagenum 当前页码
     * @return PageInfo<Borrow> 借阅中的记录分页信息
     */
    public PageInfo<Borrow> getUserCurrentBorrows(Integer userid, Integer pagenum) {
        PageHelper.startPage(pagenum, 10, "borrowTime desc");
        List<Borrow> list = borrowMapper.selectByUserId(userid, true, false); // returntimeIsNull = true
        populateBookAndUserNames(list); // 填充书名、用户名和状态
        return new PageInfo<>(list);
    }

    /**
     * 获取用户已归还的图书 (分页) - returnTime IS NOT NULL
     * @param userid 用户ID
     * @param pagenum 当前页码
     * @return PageInfo<Borrow> 已归还的记录分页信息
     */
    public PageInfo<Borrow> getUserReturnedBorrows(Integer userid, Integer pagenum) {
        PageHelper.startPage(pagenum, 10, "borrowTime desc");
        List<Borrow> list = borrowMapper.selectByUserId(userid, false, true); // returntimeIsNotNull = true
        populateBookAndUserNames(list); // 填充书名、用户名和状态
        return new PageInfo<>(list);
    }
}